package service.Register;
import backend.DuplicatedItem;
import backend.GeneralDatabase;
import backend.DiseaseItem;
import backend.EmptyOutput;

import java.util.regex.Pattern;

public class RegisterService {
    private final GeneralDatabase database;
    public RegisterService(GeneralDatabase database) {
        this.database = database;
    }
    public RegisterResult registerUser(String username, String password, String confirmPassword) {
        try {
            validateInputs(username, password, confirmPassword);

            String result = database.tryRigister(username, password);
            if ("SUCCESS".equals(result)) {
                return RegisterResult.success();
            } else if ("USER_EXISTS".equals(result)) {
                return RegisterResult.userExists(username);
            }
            return RegisterResult.error("注册失败");
        } catch (DuplicatedItem e) {
            return RegisterResult.userExists(e.getMessage());
        } catch (EmptyOutput | NumberFormatException e) {
            return RegisterResult.invalidInput(e.getMessage());
        } catch (Exception e) {
            return RegisterResult.error("系统错误: " + e.getMessage());
        }
    }

    private void validateInputs(String username, String password, String confirmPassword) throws EmptyOutput {
        if (username == null || username.isEmpty()) {
            throw new EmptyOutput("用户名为空");
        }
        if (password == null || password.isEmpty()) {
            throw new EmptyOutput("密码为空");
        }
        if (!password.equals(confirmPassword)) {
            throw new EmptyOutput("两次输入的密码不一致");
        }
        if (!isPasswordValid(password)) {
            throw new EmptyOutput("密码不符合要求");
        }
    }

    private boolean isPasswordValid(String password) {
        if (password.length() < 8) return false;
        return Pattern.matches(".*[A-Z].*", password) &&
                Pattern.matches(".*[a-z].*", password) &&
                Pattern.matches(".*\\d.*", password) &&
                Pattern.matches(".*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>\\/?].*", password);
    }
}
